﻿using Gasgoo.ShareLibrary.Framework.iDataProvider;
using SqlSugar;
using System;
using System.Linq;

namespace Gasgoo.DataProvider.SqlSugar
{

    internal static class SqlSugarUtils<T> where T : SqlSugarClient
    {
        static object _lock = new object();
        static bool isChecked = false;
        internal static void CheckDatabaseAndStructure(SqlSugarClient client)
        {
            if (isChecked) return;

            lock (_lock)
            {
                if (isChecked) return;

                // 检查数据库
                var entitys = typeof(SqlSugarUtils<T>).Assembly
                    .GetTypes()
                    .Where(t => typeof(AbstractDataEntity).IsAssignableFrom(t))
                    .Where(t => !t.IsAbstract && t.IsClass)
                    .ToArray();

                //建库   -> 达梦和Oracle不支持建库
                client.DbMaintenance.CreateDatabase();

                //建表（看文档迁移）
                client.CodeFirst.InitTables(entitys);

                isChecked = true;
            }
        }
    }

    internal static class SqlSugarUtils
    {
        internal static ConfigureExternalServices GetConfigureExternalServices()
        {
            AbstractDataEntity? entity = null;
            return new ConfigureExternalServices()
            {
                EntityService = (property, column) =>
                {
                    if (string.Compare(column.PropertyName, nameof(entity.PrimaryKey)) == 0)
                    {
                        column.IsPrimarykey = true;
                    }

                    if (string.Compare(column.PropertyName, nameof(entity.CreateDate)) == 0)
                    {
                        column.InsertServerTime = true;
                        column.IsOnlyIgnoreUpdate = true;
                    }

                    if (string.Compare(column.PropertyName, nameof(entity.ModifyDate)) == 0)
                    {
                        column.UpdateServerTime = true;
                    }

                    if (column.IsPrimarykey == false && property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        column.IsNullable = true;
                    }

                    if (property.PropertyType == typeof(string) && column.IsPrimarykey == false)
                    {
                        column.IsNullable = true;
                    }
                }
            };
        }
    }

}
